package com.travel.controller;

import com.travel.common.Result;
import com.travel.domain.DTO.MailDTO;
import com.travel.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 发送验证码
    @PostMapping("/sendCode")
    public Result<String> sendCode(@RequestBody MailDTO mailDTO) {
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(999999));

        // 存入 Redis，设置过期时间为 5 分钟
        redisTemplate.opsForValue().set("email:code:" + mailDTO.getEmail(), code, 5, TimeUnit.MINUTES);

        // 发送邮件
        boolean result = mailUtil.sendEmailCode(code, mailDTO.getEmail());

        if (result) {
            return Result.success("验证码发送成功！");
        } else {
            return Result.error("验证码发送失败，请重试！");
        }
    }

    // 验证验证码
    @PostMapping("/verifyCode")
    public Result<String> verifyCode(@RequestBody MailDTO mailDTO) {
        // 从 Redis 获取验证码
        String redisCode = redisTemplate.opsForValue().get("email:code:" + mailDTO.getEmail());

        if (redisCode == null) {
            return Result.error("验证码已过期，请重新获取！");
        }

        if (!redisCode.equals(mailDTO.getCode())) {
            return Result.error("验证码错误，请重新输入！");
        }

        // 验证成功后，可以清除 Redis 中的验证码
        redisTemplate.delete("email:code:" + mailDTO.getEmail());

        return Result.success("验证成功！");
    }
}
